import { Component, OnInit } from '@angular/core';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { HttpService } from '@core/services/http.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

import swal from "sweetalert2";
// import { qq } from '../../maps/qq/qq.component';

@Component({
  selector: 'app-class-management',
  templateUrl: './class-management.component.html'
})

export class ClassManagementComponent implements OnInit {
    validateForm: FormGroup;
    style: any = {
        width: '70%'
    };
    searchOptions = [];
    selectedMultipleOption = [];
    popTitle;
    loading = false;
    modalVisible2 = false;
    Cname = '';
    CId = '';

    _allChecked = false;
    _indeterminate = false;
    _displayData = [];
    _checkTable = [];
    _checkLength = 0;

    _allCheckedStu = false;
    _indeterminateStu = false;
    _displayDataStu = [];
    _checkTableStu = [];
    _checkLengthStu = 0;

    IP_PORT = this.http.IP_PORT;
    saveState = '';
    searchValue = '';
    ids = [];
    stus = [];
    _loading = false;
    showStudents = false;
    showClass  = false;
    stu_loading = false;
    data = [];
    className;
    student = [];
    classList = [];
    addIds = [];
    tableA;
    tableAPi = 1;
    tableAPs = 10;
    cla_id;
    class_id;
    ngOnInit() {
        this.validateForm = this.fb.group({
            C_name : [ null, [ Validators.required ] ]
        });
        this.getData();
    }

    getFormControl(name) {
        return this.validateForm.controls[ name ];
    }

    getData() {
        this._loading = true;
        let param = {pi: this.tableAPi, ps: this.tableAPs, key: this.searchValue, deviceType:'pc'};
        this.http.classList(param).subscribe(res => {
            this._loading = false;
            if (res.list.length === 0 && this.tableAPi !== 1 ){
                this.tableAPi -= 1;
                this.getData();
            } else {
                this.data = res.list;
                this._displayData = res.list;
                this.tableA = res.total;
            }
        });
    }

    save() {
        for (let i in this.selectedMultipleOption) {
            let item = this.selectedMultipleOption[i].toString()
            this.addIds.push(item);
        }
        if (this.saveState === 'add') {
            if (this.validateForm.valid) {
                this.loading = true;
                let param = {cour_id: this.addIds, cla_name: this.Cname};
                this.http.AddClass(param).subscribe(res => {
                    if (res.code == 0) {
                        this.modalVisible2 = false;
                        this.loading = false;
                        this.createMessage('success', res.msg);
                        this.getData();
                    }else {
                        this.modalVisible2 = false;
                        this.loading = false;
                        this.createMessage('error', res.msg);
                        this.getData();
                    }
                });
            } else {
                this.loading = false;
                this.createMessage('error', '请输入完整内容后再保存！');
            }

        }else {
            if (this.validateForm.valid) {
                let params = {cla_name: this.Cname, cla_id: this.CId.toString(), cour_id: this.addIds};
                this.http.updateClassByClaId(params).subscribe(res => {
                    if (res.code == 0) {
                        this.modalVisible2 = false;
                        this.loading = false;
                        this.createMessage('success', res.msg);
                        this.getData();
                    }else {
                        this.modalVisible2 = false;
                        this.loading = false;
                        this.createMessage('error', res.msg);
                        this.getData();
                    }
                });
            }else {
                this.loading = false;
                this.createMessage('error', '请输入完整内容后再保存！');
            }
        }
    }

    modal (state, data) {
        this.addIds = [];
        if (state === 'add') {
            let param = {pi: 1, ps: 10};
            this.http.getCourseListByUid(param).subscribe(res => {
                this.searchOptions = res.list;
            });
            this.modalVisible2 = true;
            this.Cname = '';
            this.selectedMultipleOption = [];
            this.popTitle = '新建班级';
            this.saveState = 'add';
        }else if (state === 'update') {
            this.addIds = [];
            let param = {pi: 1, ps: 10, cla_id: data.cla_id};
            this.selectedMultipleOption = [];
            this.http.getSelectOfCourListByClaId(param).subscribe(res => {
                this.searchOptions = res.list;
                for (let ser in this.searchOptions) {
                    if (this.searchOptions[ser].ischeck === 1) {
                        this.selectedMultipleOption.push(this.searchOptions[ser].cour_id);
                    }
                }
            });
            this.modalVisible2 = true;
            this.popTitle = '修改班级';
            this.CId = data.cla_id;
            this.Cname = data.cla_name;
            this.saveState = 'update';
        }

    }

    search () {
        this.getData();
    }

    delClassById (data) {
        let param = { cla_id: data.cla_id.toString()};
        this.http.deleteClassById(param).subscribe(res => {
            if (res.code == 0) {
                this.createMessage('success', res.msg);
                this.getData();
                param = null;
            }else {
                this.createMessage('error', res.msg);
                param = null;
            }
        });
    }

    showConfirm = (data) => {
        let that = this;
        this.confirmServ.confirm({
            title  : '您是否确认要删除这项内容',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                that.delClassById (data);
            },
            onCancel() {
            }
        });
    };

    _displayDataChange($event) {
        this._displayData = $event;
        this._refreshStatus();
    }

    _refreshStatus() {
        const allChecked = this._displayData.every(value => value.checked === true);
        const allUnChecked = this._displayData.every(value => !value.checked);
        const checkTable = this._displayData.filter(value => value.checked);
        this._allChecked = allChecked;
        this._indeterminate = (!allChecked) && (!allUnChecked);
        this._checkTable = checkTable;
        this._checkLength = checkTable.length;
    }

    _checkAll(value) {

        if (value) {
            this._displayData.forEach(data => {
                data.checked = true;

            });
        } else {
            this._displayData.forEach(data => {
                data.checked = false;

            });
        }

        this._refreshStatus();

    }

    _refreshStatusStu(student) {
        this._displayDataStu = student;
        const allCheckedStu = this._displayDataStu.every(data => data.checked === true);
        const allUnCheckedStu = this._displayDataStu.every(data => !data.checked);
        const checkTableStu = this._displayDataStu.filter(data => data.checked);
        this._allCheckedStu = allCheckedStu;
        this._indeterminateStu = (!allCheckedStu) && (!allUnCheckedStu);
        this._checkTableStu = checkTableStu;
        this._checkLengthStu = checkTableStu.length;
        //console.log(this.student);
    }

    _checkAllStu(value) {
        this._displayDataStu = this.student;
        if (value) {
            this._displayDataStu.forEach(data => {
                data.checked = true;
            });
        } else {
            this._displayDataStu.forEach(data => {
                data.checked = false;
            });
        }
        this._refreshStatusStu(this.student);
    }

    deleteStuByStuId () {

        this.stus = [];
        this._checkTableStu.map(m => {
            this.stus.push(m.Id.toString());
        });
        let param = { cla_id: this.cla_id , stuId: this.stus};

        this.http.deleteStuOfClaAndCour(param).subscribe(res => {

            if (res.code == 0) {
                this.createMessage('success', res.msg);
                swal(`${res['msg']}`, '', 'info');
                //console.log('del-----'+this.cla_id);
                this.stuRefresh(this.cla_id) ;
                this._allCheckedStu = false;
                this._indeterminateStu = false;
                param = null;
            }else {
                this.createMessage('error', res.msg);
                param = null;
            }
        });
    }

    allDeleteStu () {
        let that = this;
        this.confirmServ.confirm({
            title  : '您是否确认要批量删除选中的' + this._checkLengthStu + '项内容？',
            okText : '确定',
            cancelText: '取消',
            onOk: () => {
                that.deleteStuByStuId();
            },
            onCancel() {
            }
        });
    }

    deleteClaListByClaId () {
        this.ids = [];
        this._checkTable.map(m => {
            this.ids.push(m.cla_id.toString());
        });
        let param = { cla_id: this.ids};
        this.http.deleteClaListByClaId(param).subscribe(res => {
            if (res.code == 0) {
                this.createMessage('success', res.msg);
                this.getData();
                param = null;
            }else {
                this.createMessage('error', res.msg);
                param = null;
            }
        });
    }

    allDelete () {
        let that = this;
        this.confirmServ.confirm({
            title  : '您是否确认要批量删除选中的' + this._checkLength + '项内容？',
            okText : '确定',
            cancelText: '取消',
            onOk: () => {
                that.deleteClaListByClaId();
            },
            onCancel() {
            }
        });
    }

    createMessage = (type, text) => {
        this._message.create(type, `${text}`);
    }

    stuShow (data) {

        this.className = data.cla_name;
        this.cla_id = data.cla_id;
        this.showStudents = true;

        let param = {pi: 1, ps: 9999, cla_id: data.cla_id};
        this._loading = true;
        this.http.getStuListByClaId(param).subscribe(res => {

            this._allCheckedStu = false; /*初始化删除学生的全选按钮*/
            this._indeterminateStu = false; /*初始化删除学生的全选按钮*/

            this.student = res.list;
            this._loading = false;
        });
    }
    stuRefresh (data) {
        //console.log("stuShow ------"+data);
        this.className = data.cla_name;
        this.cla_id = data.cla_id;
        this.showStudents = true;

        let param = {pi: 1, ps: 9999, cla_id: data};
        this._loading = true;
        this.http.getStuListByClaId(param).subscribe(res => {
            this.student = res.list;
            this._loading = false;
        });
    }

    play (data) {

       // console.log(data)
        let cla_id = this.class_id;
        let p_id = data.p_id;
        let p_type = JSON.parse(data.p_type).value;
        let cour_id = data.cour_id;
        let token =JSON.parse(localStorage.getItem('_user')).access_token;
       // console.log('cid---'+ cla_id + 'pid----' + p_id +'p_type---' + p_type 'courid----'+ cour_id)
        this.confirmServ.confirm({

            title  : '您是否确定演练该项目',
            okText : '确定',
            cancelText: '取消',
            onOk: ()=>{

                this.http.quickEntryProject({cla_id:cla_id ,p_type:p_type ,cour_id:cour_id,day:'1' ,exercisetypes:'0' ,p_id:p_id , deviceType:'pc',token:token}).subscribe(data => {
                    //  console.log(data);

               })


           },
           onCancel() {

           }
       });

    }

    courLists(data) {
        this.class_id = data.cla_id;
        this.showClass = true;
        let param = {cla_id: data.cla_id.toString()};
        this._loading = true;
        this.http.getClaAndCourToPriProListByClaId(param).subscribe(res => {
            this.classList = res.list;
            this._loading = false;
        });
    }

    constructor(
        private confirmServ: NzModalService,
        private http: HttpService,
        private _message: NzMessageService,
        private fb: FormBuilder
    ) {
    }

}
